package eerbaar.expression.internal.lib;

import eerbaar.context.IContext;
import eerbaar.context.IParams;
import eerbaar.context.ParamFactory;
import eerbaar.shared.message.IMessageReader;
import eerbaar.shared.message.Message;
import eerbaar.shared.message.MsgHelper;

public class MessageExpression extends AbstractExpression implements
        IMessageReader {

    private static final String[] paramNames = new String[] { "name" };

    private boolean flag;

    private String messageType;

    private IParams params;

    public MessageExpression() {
        super("message");

        this.params = ParamFactory.createParams();
    }

    public MessageExpression(IParams params) {
        super("message");
        this.params = params;

        setup(params);
    }

    @Override
    public boolean execute(IContext model) {
        assert (this.messageType != null);

        return this.flag;
    }

    @Override
    public String[] getParamNames() {

        return paramNames;
    }

    @Override
    public IParams getParams() {

        return this.params;
    }

    public String getTarget() {

        return this.messageType;
    }

    @Override
    public boolean read(Message msg) {
        this.flag = true;

        return false;
    }

    @Override
    public void setParams(IParams params) {

        this.params = params;
        setup(params);
    }

    public void setTarget(String target) {

        this.messageType = target;
    }

    private void setup(IParams params) {

        this.messageType = params.get("name");
    }

    @Override
    public void start() {
        assert (this.messageType != null);

        MsgHelper.registerReader(this.messageType, this);
        this.flag = false;
    }

    @Override
    public void stop() {

        MsgHelper.unregisterReader(this.messageType, this);
    }

}
